from pathlib import Path
from datetime import datetime, timezone
import logging
import pytest
import requests
from config import datas


logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %Z'
)
logger = logging.getLogger(__name__)


# 基础配置（根据实际环境修改）
# BASE_URL = "http://192.168.100.192:30010"  # 替换为实际API地址
CREATE_CLUSTER_ENDPOINT = datas.BASE_URL + f"/rest/cluster/v1/create"  # 替换为实际创建集群的API端点

# 节点配置（作为变量传入）
# NODE_IP = "192.168.100.200"  # 实际节点IP
# NODE_PASSWORD = "test@123"  # 实际节点密码
# HTTP_REPO_IP = "192.168.100.192"  # 引导节点IP

# 获取当前脚本所在目录
SCRIPT_DIR = Path(__file__).parent.resolve()

# 从当前目录(testcases/test/v25.06/bke/)回退到项目根目录
project_root = SCRIPT_DIR.parent.parent.parent


def load_and_prepare_yaml_template():
    logger.info("开始加载并准备YAML模板")
    """加载YAML模板并进行变量替换"""
    template_path = (
            project_root /
            "data" /
            "v25.06" /
            "bke" /
            "create_cluster.yaml"
    )

    if not template_path.exists():
        error_msg = f"YAML模板文件不存在: {template_path}"
        logger.error(error_msg)
        pytest.fail(error_msg)

    # 读取模板内容
    with open(template_path, "r", encoding="utf-8") as f:
        template_content = f.read()

    # 替换占位符
    prepared_content = template_content.replace("{{NODE_IP}}", datas.NODE_IP)
    prepared_content = prepared_content.replace("{{NODE_PASSWORD}}", datas.NODE_PASSWORD)
    prepared_content = prepared_content.replace("{{HTTP_REPO_IP}}", datas.HTTP_REPO_IP)

    # 验证替换结果
    if "{{NODE_IP}}" in prepared_content:
        raise ValueError("节点密码占位符未完全替换")
    if "{{NODE_PASSWORD}}" in prepared_content:
        raise ValueError("节点密码占位符未完全替换")
    if "{{HTTP_REPO_IP}}" in prepared_content:
        raise ValueError("http IP占位符未完全替换")

    # 转换为字符串格式（如果需要，可以添加额外的处理）
    return prepared_content



def test_create_cluster_with_yaml_template():
    """使用YAML模板创建集群（带变量替换）"""
    # 1. 准备请求数据
    yaml_string = load_and_prepare_yaml_template()
    payload = {"yamlString": yaml_string}
    logger.debug("请求数据准备完成")

    # 2. 发送创建集群请求
    #start_time = datetime.now(timezone.utc)
    #print(f"[{start_time.isoformat()}] 发送创建集群请求...")

    try:
        response = requests.post(
            url=CREATE_CLUSTER_ENDPOINT,
            json=payload,
            headers={"Content-Type": "application/json"},
            timeout=60
        )
    except requests.exceptions.RequestException as e:
        pytest.fail(f"请求失败: {str(e)}")

    # 3. 验证创建响应
    if response.status_code != 200:
        raise RuntimeError(
            f"创建集群失败! 状态码: {response.status_code}, 响应: {response.text}"
        )

    #response_data = response.json()
   # print(f"[{datetime.now().isoformat()}] 集群创建请求成功: {response_data}")
